package io.renren.common.utils;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.xiaoleilu.hutool.date.DateUnit;
import com.xiaoleilu.hutool.date.DateUtil;

import io.renren.common.exception.RRException;

/**
 * 日期处理
 * 
 **/
public class DateUtils {
	/** 时间格式(yyyy-MM-dd) */
	public final static String DATE_PATTERN = "yyyy-MM-dd";
	/** 时间格式(yyyy-MM-dd HH:mm:ss) */
	public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

	public static String format(Date date) {
		return format(date, DATE_PATTERN);
	}

	public static String format(Date date, String pattern) {
		if (date != null) {
			SimpleDateFormat df = new SimpleDateFormat(pattern);
			return df.format(date);
		}
		return null;
	}

	public static int dateBetween(Date date1, Date date2) {
		if (date1.after(date2)) {
			throw new RRException("开始日期不能大于结束日期");
		}
		Long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);
		double a = Double.valueOf((betweenDay.toString())) / 30;
		DecimalFormat decimalFormat = new DecimalFormat();
		decimalFormat.setMaximumFractionDigits(1);
		decimalFormat.setGroupingSize(0);
		decimalFormat.setRoundingMode(RoundingMode.FLOOR);
		String result = decimalFormat.format(a);
		Double between = Double.valueOf(result);
		if (between.intValue() < 1) {
			return 1;
		}
		return (int) Math.round(between);
		// double y = between - between.intValue();
		// if (y * 10 < 5) {
		// return between.intValue();
		// }
		// return between.intValue() + 1;
	}

	public static int dateBetween(String dateStr1, String dateStr2) {
		Date date1 = DateUtil.parse(dateStr1);
		Date date2 = DateUtil.parse(dateStr2);
		return dateBetween(date1, date2);
	}

}
